package com.mzj.saas.mservice.contract.service;

import com.mzj.saas.commons.*;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.contract.entity.*;
import com.mzj.saas.mservice.contract.repository.*;
import com.mzj.saas.mservice.contract.vo.*;
import com.mzj.saas.mservice.eligible.entity.DepartmentHierarchy;
import com.mzj.saas.mservice.eligible.repository.DepartmentHierarchyRepository;
import com.mzj.saas.mservice.sys.service.FieldService;
import com.mzj.saas.redis.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Service
public class ContractService {
    private static final Logger LOG = LoggerFactory.getLogger(ContractService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ContractTemplateRepository contractTemplateRepository;
    @Autowired
    private DepartmentHierarchyRepository departmentHierarchyRepository;
    @Autowired
    private ContractTemplateFieldRepository contractTemplateFieldRepository;
    @Autowired
    private ContractTemplateCustomFieldRepository contractTemplateCustomFieldRepository;
    @Autowired
    private FieldService fieldService;
    @Autowired
    private ContractTemplatePaymentProjectRepository contractTemplatePaymentProjectRepository;
    @Autowired
    private ContractTemplateCustomAttachmentRepository contractTemplateCustomAttachmentRepository;
    @Autowired
    private ContractAttachmentRepository contractAttachmentRepository;
    @Autowired
    private ContractTemplateDefaultFieldRepository contractTemplateDefaultFieldRepository;

    /**
     * 实现了合同设置列表信息展示
     *
     * @param accessToken 权限鉴定
     * @param pageNumber  当前页
     * @param pageSize    页数
     * @param filter      合同设置列表条件筛查实体类
     * @return
     */
    public ResultBean<Object> contractSetShowListInfo(String accessToken, Integer pageNumber, Integer pageSize,
                                                      ContractSetSearchRequestVO filter) {
        // 操作记录日志
        LOG.info("---ContractService contractSetShowListInfo accessToken={},pageNumber={},pageSize={},filter={}",
                accessToken, pageNumber, pageSize, filter);
        ResultBean<Object> result = new ResultBean<>();
        // 模认返回成功
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        // 获取用户登录权限
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        ApiData<Map<String, Object>> apiData = new ApiData<>();
        try {
            // 用户权限的鉴定
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            // 根据用户ID查询出用户层级权限
            DepartmentHierarchy departmentHierarchy = departmentHierarchyRepository
                    .findByOrgId(tokenRedisVo.getEnterpriseId());
            if (departmentHierarchy == null) {
                return ResultBean.failedResultWithMsg("当前企业层级关系不存在");
            }
            String sql = "SELECT org_id FROM ( SELECT t1.id,t1.org_id,IF(FIND_IN_SET(parent_id, @pids) > 0,@pids := CONCAT(@pids, ',', id),0) AS ischild FROM ( SELECT id,parent_id,org_id FROM `saas_department_hierarchy` t ORDER BY parent_id, id ) t1,(SELECT @pids := ?) t2 ) t3 WHERE ischild != 0 \n";
            // 获取机构ID
            List<Long> orgIdList = jdbcTemplate.queryForList(sql, new Object[]{departmentHierarchy.getId()},
                    Long.class);
            // 获取企业ID
            orgIdList.add(tokenRedisVo.getEnterpriseId());
            String listSql = " SELECT t.`contract_template_number` AS contractTemplateNumber,t.`name`,t.`org_id` AS orgId,h.`name` AS unitName,t.`import_time` AS importTime,t.`status`,t.`content` FROM saas_contract_template t LEFT JOIN `saas_department_hierarchy` h ON t.`org_id`=h.`org_id` WHERE  1=1 AND t.`operator_status`=1  ";
            StringBuffer orgIds = new StringBuffer();
            // 遍历机构ID
            for (Long orgId : orgIdList) {
                orgIds.append(orgId).append(",");
            }

            String orgId = orgIds.substring(0, orgIds.lastIndexOf(","));
            listSql += "  AND  t.`org_id` IN (" + orgId + ")";
            String offsets = "   LIMIT ? OFFSET ? ";
            List<Object> args = new ArrayList<>();
            StringBuilder where = new StringBuilder();
            // 根据不同条件查询合同数据
            if (StringUtils.isNotBlank(filter.getContractTemplateNumber())) {
                where.append("  AND  t.`contract_template_number` like ?  \n");
                args.add("%" + filter.getContractTemplateNumber() + "%");
            }
            if (StringUtils.isNotBlank(filter.getName())) {
                where.append("  AND  t.`name` like ?  \n");
                args.add("%" + filter.getName() + "%");
            }
            if (filter.getOrgId() != null) {
                where.append("  AND  t.`org_id` =  ?  \n");
                args.add(filter.getOrgId());
            }
            // 查询总记录数
            String count = "select count(1) FROM (" + listSql + where + ") c  ";
            Long total = jdbcTemplate.queryForObject(count, Long.class, args.toArray());
            LOG.info("SQL :" + sql + where);
            if (total == 0) {
                result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
                result.setResultData(null);
                return result;
            }
            // 查询分页数据
            where.append("  ORDER BY ").append(" t.import_time desc ").append(" \n").append(offsets);
            // 设置当前页
            args.add(pageSize);
            // 设置页数
            args.add(pageNumber * pageSize);
            List<Map<String, Object>> peopleList = jdbcTemplate.queryForList(listSql + where, args.toArray());
            apiData.setData(peopleList);
            apiData.setTotal(total);
            LOG.info("SQL :" + sql + where);
            result.setResultData(apiData);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 修改合同状态
     *
     * @param accessToken            权限鉴定
     * @param status                 0禁用 1启用  默认启用
     * @param contractTemplateNumber 模板合同序号
     * @return
     */
    public ResultBean<Object> changeContractSetStatus(String accessToken, Integer status,
                                                      String contractTemplateNumber) {
        // 记录操作日志
        LOG.info("---ContractService changeContractSetStatus accessToken={},status={},contractTemplateNumber={}",
                accessToken, status, contractTemplateNumber);
        // 默认返回成功
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        // 获取用户登录权限
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            // 用户权限的鉴定
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            // 判断合同是否存在
            if (status == null || StringUtils.isBlank(contractTemplateNumber)) {
                result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                return result;
            }
            // 根据合同编号获取合同数据
            ContractTemplate existContractTemplate = contractTemplateRepository
                    .findByContractTemplateNumber(contractTemplateNumber);
            if (existContractTemplate == null) {
                return ResultBean.failedResultWithMsg("合同模板信息不存在");
            }
            // 设置合同参数
            existContractTemplate.setStatus(status);
            existContractTemplate.setLastUpdateTime(new Date());
            existContractTemplate.setOperatorId(tokenRedisVo.getId());
            contractTemplateRepository.save(existContractTemplate);
        } catch (Exception e) {
            // 记录错误日志
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 合同模板删除,删除模板
     *
     * @param accessToken            权限鉴定
     * @param contractTemplateNumber 模板合同序号
     * @return
     */
    public ResultBean<Object> deleteContractTemplate(String accessToken, String contractTemplateNumber) {
        // 记录操作日志
        LOG.info("---ContractService deleteContract accessToken={},contractTemplateNumber={}", accessToken,
                contractTemplateNumber);
        // 默认成功
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            // 获取用户登录权限
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            // 判断合同是否存在
            if (StringUtils.isBlank(contractTemplateNumber)) {
                result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                return result;
            }
            // 根据合同编号获取合同数据
            ContractTemplate existContractTemplate = contractTemplateRepository
                    .findByContractTemplateNumber(contractTemplateNumber);
            if (existContractTemplate == null) {
                return ResultBean.failedResultWithMsg("合同模板信息不存在");
            }
            // 删除模块数据
            existContractTemplate.setOperatorStatus(2);
            existContractTemplate.setLastUpdateTime(new Date());
            existContractTemplate.setOperatorId(tokenRedisVo.getId());
            contractTemplateRepository.save(existContractTemplate);
        } catch (Exception e) {
            // 记录报错日志
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 合同字段显示,实现了合同字段的详细显示
     *
     * @param accessToken            权限鉴定
     * @param contractTemplateNumber 合同编号
     * @return
     */
    public ResultBean<Object> contractFieldShow(String accessToken, String contractTemplateNumber) {
        // 记录操作日志
        LOG.info("---ContractService contractFieldShow accessToken={},contractTemplateNumber={}", accessToken,
                contractTemplateNumber);
        // 默认操作成功
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        // 获取用户登录权限
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            // 用户权限的鉴定
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            // 判断合同是否存在
            if (StringUtils.isBlank(contractTemplateNumber)) {
                result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                return result;
            }
            // 根据合同编号获取合同数据
            ContractTemplate existContractTemplate = contractTemplateRepository
                    .findByContractTemplateNumber(contractTemplateNumber);
            if (existContractTemplate == null) {
                return ResultBean.failedResultWithMsg("合同模板信息不存在");
            }
            String sql = "(SELECT t.id,f.`field_name` AS fieldName,f.`name`,f.`show_status` AS showStatus ,t.`must_status` AS mustStatus,0 AS `type` FROM `saas_contract_template_field` t  INNER JOIN  `saas_contract_template_default_field` f ON t.`default_id`=f.id  WHERE t.`contract_template_number`=? ) UNION ALL ( SELECT c.id,c.`field_name` AS fieldName,c.`name`,c.`show_status` AS showStatus,c.`must_status` AS mustStatus,1 AS `type` FROM `saas_contract_template_custom_field` c WHERE STATUS=1 AND `contract_template_number`=?  )\n";
            // 获取合同数据
            List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql,
                    new Object[]{existContractTemplate.getContractTemplateNumber(),
                            existContractTemplate.getContractTemplateNumber()});
            // 设置存储数据
            result.setResultData(mapList);
        } catch (Exception e) {
            // 记录报错日志
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        // 把数据返回给前端页面
        return result;
    }

    /*
     * 修改合同字段状态
     */
    public ResultBean<Object> changeContractStatus(String accessToken,
                                                   FieldStatusSetRequestVO fieldStatusSetRequestVO) {
        LOG.info("---ContractService changeContractStatus accessToken={},fieldStatusSetRequestVO={}", accessToken,
                fieldStatusSetRequestVO);
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            if (fieldStatusSetRequestVO == null) {
                result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                return result;
            }
            if (StringUtils.isBlank(fieldStatusSetRequestVO.getContractTemplateNumber())
                    || fieldStatusSetRequestVO.getId() == null || fieldStatusSetRequestVO.getOperatorType() == null
                    || fieldStatusSetRequestVO.getStatus() == null || fieldStatusSetRequestVO.getType() == null) {
                result.setCode(StatusCode.ERROR_CODE_10004.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_10004.getErrorMsg());
                return result;
            }
            ContractTemplate existContractTemplate = contractTemplateRepository
                    .findByContractTemplateNumber(fieldStatusSetRequestVO.getContractTemplateNumber());
            if (existContractTemplate == null) {
                return ResultBean.failedResultWithMsg("合同模板信息不存在");
            }
            // 默认字段
            if (fieldStatusSetRequestVO.getType() == 0) {
                ContractTemplateField contractTemplateField = contractTemplateFieldRepository
                        .findById(fieldStatusSetRequestVO.getId()).get();
                contractTemplateField.setMustStatus(fieldStatusSetRequestVO.getStatus());
                contractTemplateField.setOperatorId(tokenRedisVo.getId());
                contractTemplateField.setLastUpdateTime(new Date());
                contractTemplateField.setUpdateUserId(tokenRedisVo.getId());
                contractTemplateFieldRepository.save(contractTemplateField);
            } else {
                // 自定义字段
                ContractTemplateCustomField contractTemplateCustomField = contractTemplateCustomFieldRepository
                        .findById(fieldStatusSetRequestVO.getId()).get();
                if (fieldStatusSetRequestVO.getOperatorType() == 0) {
                    // 显示状态操作
                    contractTemplateCustomField.setShowStatus(fieldStatusSetRequestVO.getStatus());
                } else if (fieldStatusSetRequestVO.getOperatorType() == 1) {
                    // 必填状态操作
                    contractTemplateCustomField.setMustStatus(fieldStatusSetRequestVO.getStatus());
                } else if (fieldStatusSetRequestVO.getOperatorType() == 2) {
                    contractTemplateCustomField.setStatus(fieldStatusSetRequestVO.getStatus());
                }
                contractTemplateCustomField.setOperatorId(tokenRedisVo.getId());
                contractTemplateCustomField.setLastUpdateTime(new Date());
                contractTemplateCustomField.setUpdateUserId(tokenRedisVo.getId());
                contractTemplateCustomFieldRepository.save(contractTemplateCustomField);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 新增合同字段
     *
     * @param accessToken            权限鉴定
     * @param contractTemplateNumber 合同编号
     * @param name                   名称
     * @return
     */
    public ResultBean<Object> addContractField(String accessToken, String contractTemplateNumber, String name) {
        // 记录操作日志
        LOG.info("---ContractService addContractField accessToken={},contractTemplateNumber={},name={}", accessToken,
                contractTemplateNumber, name);
        // 默认返回成功
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            // 获取用户登录权限
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            // 判断合同编号或者名称是否为空
            if (StringUtils.isBlank(contractTemplateNumber) || StringUtils.isBlank(name)) {
                result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                return result;
            }
            // 根据合同编号获取合同数据
            ContractTemplate existContractTemplate = contractTemplateRepository
                    .findByContractTemplateNumber(contractTemplateNumber);
            if (existContractTemplate == null) {
                return ResultBean.failedResultWithMsg("合同模板信息不存在");
            }
            // 获取合同数据
            ContractTemplateCustomField existContractTemplateCustomField = contractTemplateCustomFieldRepository
                    .findByContractTemplateNumberAndName(contractTemplateNumber, name);
            if (existContractTemplateCustomField != null && existContractTemplateCustomField.getStatus() == 1) {
                return ResultBean.failedResultWithMsg("该字段已存在");
                //	设置合同字段
            } else if (existContractTemplateCustomField != null && existContractTemplateCustomField.getStatus() == 2) {
                existContractTemplateCustomField.setStatus(1);
                existContractTemplateCustomField.setOperatorId(tokenRedisVo.getId());
                existContractTemplateCustomField.setUpdateUserId(tokenRedisVo.getId());
                existContractTemplateCustomField.setLastUpdateTime(new Date());
                contractTemplateCustomFieldRepository.save(existContractTemplateCustomField);
            } else {
                //	设置合同字段
                ContractTemplateCustomField contractTemplateCustomField = new ContractTemplateCustomField();
                String fieldName = fieldService.pinyin(name);
                contractTemplateCustomField.setContractTemplateNumber(contractTemplateNumber);
                contractTemplateCustomField.setFieldName(fieldName);
                contractTemplateCustomField.setName(name);
                contractTemplateCustomField.setShowStatus(1);
                contractTemplateCustomField.setMustStatus(1);
                contractTemplateCustomField.setCreateTime(new Date());
                contractTemplateCustomField.setStatus(1);
                contractTemplateCustomField.setOperatorId(tokenRedisVo.getId());
                contractTemplateCustomField.setUpdateUserId(tokenRedisVo.getId());
                contractTemplateCustomField.setLastUpdateTime(new Date());
                contractTemplateCustomFieldRepository.save(contractTemplateCustomField);
            }
        } catch (Exception e) {
            // 记录报错日志
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /*
     * 查看缴费项目
     */
    public ResultBean<Object> showPayProject(String accessToken, String contractTemplateNumber) {
        LOG.info("---ContractService showPayProject accessToken={},contractTemplateNumber={}", accessToken,
                contractTemplateNumber);
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            if (StringUtils.isBlank(contractTemplateNumber)) {
                result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                return result;
            }
            ContractTemplate existContractTemplate = contractTemplateRepository
                    .findByContractTemplateNumber(contractTemplateNumber);
            if (existContractTemplate == null) {
                return ResultBean.failedResultWithMsg("合同模板信息不存在");
            }
            List<ContractTemplatePaymentProject> allPayProject = contractTemplatePaymentProjectRepository
                    .findByContractTemplateNumber(contractTemplateNumber);
            result.setResultData(allPayProject);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /*
     * 缴费项目保存接口
     */
    public ResultBean<Object> savePayProject(String accessToken, PayProjectSaveRequestVO payProjectSaveRequestVO) {
        LOG.info("---ContractService savePayProject accessToken={},payProjectSaveRequestVO={}", accessToken,
                payProjectSaveRequestVO);
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            if (payProjectSaveRequestVO == null || payProjectSaveRequestVO != null
                    && StringUtils.isBlank(payProjectSaveRequestVO.getContractTemplateNumber())) {
                result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                return result;
            }
            String contractTemplateNumber = payProjectSaveRequestVO.getContractTemplateNumber();
            ContractTemplate existContractTemplate = contractTemplateRepository
                    .findByContractTemplateNumber(contractTemplateNumber);
            if (existContractTemplate == null) {
                return ResultBean.failedResultWithMsg("合同模板信息不存在");
            }
            contractTemplatePaymentProjectRepository.deleteByContractTemplateNumber(contractTemplateNumber);
            for (Integer type : payProjectSaveRequestVO.getTypes()) {
                ContractTemplatePaymentProject contractTemplatePaymentProject = new ContractTemplatePaymentProject();
                contractTemplatePaymentProject.setContractTemplateNumber(contractTemplateNumber);
                contractTemplatePaymentProject.setType(type);
                contractTemplatePaymentProject.setOperatorId(tokenRedisVo.getId());
                contractTemplatePaymentProject.setUpdateUserId(tokenRedisVo.getId());
                contractTemplatePaymentProject.setLastUpdateTime(new Date());
                contractTemplatePaymentProjectRepository.save(contractTemplatePaymentProject);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /*
     * 合同附件查看
     */
    public ResultBean<Object> contractAttachmentShow(String accessToken, String contractTemplateNumber) {
        LOG.info("---ContractService contractAttachmentShow accessToken={},contractTemplateNumber={}", accessToken,
                contractTemplateNumber);
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            if (StringUtils.isBlank(contractTemplateNumber)) {
                result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                return result;
            }
            ContractTemplate existContractTemplate = contractTemplateRepository
                    .findByContractTemplateNumber(contractTemplateNumber);
            if (existContractTemplate == null) {
                return ResultBean.failedResultWithMsg("合同模板信息不存在");
            }
            String sql = "(SELECT ta.`id`,ca.`name`,ca.`unit`,ca.`current_situation` AS currentSituation,ca.`unit_price` AS unitPrice,ta.type,ta.`operator_status` AS operatorStatus FROM `saas_contract_template_custom_attachment` ta INNER JOIN `saas_contract_attachment` ca ON ta.`attachment_id`=ca.id  WHERE ta.status=1 AND ta.`contract_template_number`=? ) UNION ALL (SELECT ta.`id`,ta.`name`,ta.`unit`,ta.`current_situation` AS currentSituation,ta.`unit_price` AS unitPrice,ta.type,ta.`operator_status` AS operatorStatus FROM `saas_contract_template_custom_attachment` ta WHERE ta.status=1 AND TYPE=2 AND ta.`contract_template_number`=? )";
            List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql,
                    new Object[]{contractTemplateNumber, contractTemplateNumber});
            result.setResultData(mapList);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /*
     * 删除自定义附件
     */
    public ResultBean<Object> deleteContractAttachment(String accessToken, String contractTemplateNumber, Long id) {
        LOG.info("---ContractService deleteContractAttachment accessToken={},contractTemplateNumber={},id={}",
                accessToken, contractTemplateNumber, id);
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            if (StringUtils.isBlank(contractTemplateNumber) || id == null) {
                result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                return result;
            }
            ContractTemplate existContractTemplate = contractTemplateRepository
                    .findByContractTemplateNumber(contractTemplateNumber);
            if (existContractTemplate == null) {
                return ResultBean.failedResultWithMsg("合同模板信息不存在");
            }
            Optional<ContractTemplateCustomAttachment> existContractTemplateCustomAttachment = contractTemplateCustomAttachmentRepository
                    .findById(id);
            if (existContractTemplateCustomAttachment == null) {
                return ResultBean.failedResultWithMsg("字段信息不存在或是已删除");
            }
            ContractTemplateCustomAttachment contractTemplateCustomAttachment = existContractTemplateCustomAttachment
                    .get();
            contractTemplateCustomAttachment.setStatus(2);
            contractTemplateCustomAttachmentRepository.save(contractTemplateCustomAttachment);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /*
     * 合同附件保存接口
     */
    public ResultBean<Object> saveContractAttachment(String accessToken,
                                                     List<ContractAttachmentSaveRequestVO> contractAttachmentSaveRequestVOS) {
        LOG.info("---ContractService saveContractAttachment accessToken={},contractAttachmentSaveRequestVOS={}",
                accessToken, contractAttachmentSaveRequestVOS);
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            if (contractAttachmentSaveRequestVOS == null) {
                result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                return result;
            }
            for (ContractAttachmentSaveRequestVO contractAttachmentSaveRequestVO : contractAttachmentSaveRequestVOS) {
                Optional<ContractTemplateCustomAttachment> existContractTemplateCustomAttachment = contractTemplateCustomAttachmentRepository
                        .findById(contractAttachmentSaveRequestVO.getId());
                if (existContractTemplateCustomAttachment != null) {
                    ContractTemplateCustomAttachment contractTemplateCustomAttachment = existContractTemplateCustomAttachment
                            .get();
                    contractTemplateCustomAttachment
                            .setOperatorStatus(contractAttachmentSaveRequestVO.getOperatorStatus());
                    contractTemplateCustomAttachmentRepository.save(contractTemplateCustomAttachment);
                }
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 新增附件
     *
     * @param accessToken                        权限鉴定
     * @param contractTemplateCustomAttachmentVO 合同模板附件实体类
     * @return
     */
    public ResultBean<Object> addContractAttachment(String accessToken,
                                                    ContractTemplateCustomAttachmentVO contractTemplateCustomAttachmentVO) {
        // 记录操作日志
        LOG.info("---ContractService addContractAttachment accessToken={},contractTemplateCustomAttachmentVO={}",
                accessToken, contractTemplateCustomAttachmentVO);
        // 默认返回成功
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        // 获取用户登录权限
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            // 用户权限的鉴定
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            // 判断附件是否为空
            if (contractTemplateCustomAttachmentVO == null) {
                result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                return result;
            }
            // 判读合同参数是否为空
            if (StringUtils.isBlank(contractTemplateCustomAttachmentVO.getName())) {
                return ResultBean.failedResultWithMsg("名称不能为空");
            }
            if (StringUtils.isBlank(contractTemplateCustomAttachmentVO.getUnit())) {
                return ResultBean.failedResultWithMsg("单位不能为空");
            }
            if (StringUtils.isBlank(contractTemplateCustomAttachmentVO.getCurrentSituation())) {
                return ResultBean.failedResultWithMsg("现状不能为空");
            }
            if (StringUtils.isBlank(contractTemplateCustomAttachmentVO.getUnitPrice())) {
                return ResultBean.failedResultWithMsg("单价不能为空");
            }
            // 通过模板合同序号查询合同模板数据
            ContractTemplate existContractTemplate = contractTemplateRepository
                    .findByContractTemplateNumber(contractTemplateCustomAttachmentVO.getContractTemplateNumber());
            if (existContractTemplate == null) {
                return ResultBean.failedResultWithMsg("合同模板信息不存在");
            }
            // 通过合同名称查询合同附件
            ContractAttachment defaultAttachment = contractAttachmentRepository
                    .findByName(contractTemplateCustomAttachmentVO.getName());
            // 通过合同名称查询自定义合同附件
            ContractTemplateCustomAttachment customAttachment = contractTemplateCustomAttachmentRepository
                    .findByContractTemplateNumberAndName(contractTemplateCustomAttachmentVO.getContractTemplateNumber(),
                            contractTemplateCustomAttachmentVO.getName());
            // 判断合同附件是否存储
            if (defaultAttachment != null || customAttachment != null && customAttachment.getStatus() == 1) {
                return ResultBean.failedResultWithMsg("该附件已存在");
            }
            if (customAttachment != null && customAttachment.getStatus() == 2) {
                contractTemplateCustomAttachmentVO.setId(customAttachment.getId());
                contractTemplateCustomAttachmentVO
                        .setContractTemplateNumber(customAttachment.getContractTemplateNumber());
            }
            // 设置自定义合同附件并保存
            contractTemplateCustomAttachmentVO.setType(2);
            contractTemplateCustomAttachmentVO.setStatus(1);
            contractTemplateCustomAttachmentVO.setOperatorStatus(1);
            contractTemplateCustomAttachmentVO.setOperatorId(tokenRedisVo.getId());
            contractTemplateCustomAttachmentVO.setUpdateUserId(tokenRedisVo.getId());
            contractTemplateCustomAttachmentVO.setLastUpdateTime(new Date());
            ContractTemplateCustomAttachment contractTemplateCustomAttachment = new ContractTemplateCustomAttachment();
            BeanUtils.copyProperties(contractTemplateCustomAttachmentVO, contractTemplateCustomAttachment);
            contractTemplateCustomAttachmentRepository.save(contractTemplateCustomAttachment);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * word模板下载,实现了合同模板的下载
     *
     * @param accessToken 权限鉴定
     */
    public void wordDownLoad(String accessToken) {
        // 记录操作日志
        LOG.info("---DepartmentService wordDownLoad accessToken={}", accessToken);
        try {
            // 读到流中,读取我们路径中的模板文件contract.docx
            InputStream in = this.getClass().getClassLoader()
                    .getResourceAsStream("static/exceltemplates/contract.docx");
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                    .getResponse();
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            // 导出文件下载
            DownloadUtil downloadUtil = new DownloadUtil();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            // 读取输入流数据后写到内存中
            byte[] b = new byte[1024];
            int len;
            try {
                // 将内容读取到b中
                while ((len = in.read(b)) > 0)
                    bos.write(b, 0, len);
                in.close();
            } catch (IOException e) {
                LOG.error("Download the document is failed,message:{}", e.getMessage());
            }
            // 将内存中的数据写入到template.docx中
            downloadUtil.download(bos, response, "template.docx");
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }

    /*
     * 导入合同模板
     */
    public ResultBean<Object> wordImport(String accessToken, MultipartFile file) {
        LOG.info("---ContractService wordImport accessToken={},file={}", accessToken, file);
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            if (file == null) {
                return ResultBean.failedResultWithMsg("导入文件异常");
            }
            if (!file.getOriginalFilename().contains(".docx")) {
                return ResultBean.failedResultWithMsg("导入文件类型异常，请使用下载模板");
            }
            try {
                // 新增合同模板
                ContractTemplate contractTemplate = new ContractTemplate();
                contractTemplate.setContractTemplateNumber("XS" + KeyWorker.nextId());
                StringBuffer content = new StringBuffer();
                InputStream inputStream = file.getInputStream();
                XWPFDocument xwpfDocument = new XWPFDocument(inputStream);
                List<XWPFParagraph> paragraphs = xwpfDocument.getParagraphs();
                String name = "";
                for (XWPFParagraph para : paragraphs) {
                    // 当前段落的属性
                    List<XWPFRun> runsLists = para.getRuns();// 获取段楼中的句列表
                    for (XWPFRun runsList : runsLists) {
                        // String c = runsList.getColor();//获取句的字体颜色
                        int f = runsList.getFontSize();// 获取句中字的大小
                        // System.out.println(runsList.getFontName());
                        String s = runsList.getText(0);// 获取文本内容
                        content.append(s);

                    }
                    content.append("\n");
                }
                name = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));

                // System.out.println(WordToHtml.Word2007ToHtml(MultipartFileToFile.multipartFileToFile(file)));
                // for (int i = 0; i < paragraphs.size(); i++) {
                // name = paragraphs.get(0).getText();
                // content.append(paragraphs.get(i).getText());
                // }
                contractTemplate.setOrgId(tokenRedisVo.getEnterpriseId());
                contractTemplate.setContent(String.valueOf(content));
                contractTemplate.setName(name);
                contractTemplate.setStatus(1);
                contractTemplate.setOperatorStatus(1);
                contractTemplate.setImportTime(new Date());
                contractTemplate.setOperatorId(tokenRedisVo.getId());
                contractTemplate.setLastUpdateTime(new Date());
                ContractTemplate template = contractTemplateRepository.save(contractTemplate);
                if (template != null) {
                    // 生成合同缴费项目
                    for (int i = 1; i < 8; i++) {
                        ContractTemplatePaymentProject contractTemplatePaymentProject = new ContractTemplatePaymentProject();
                        contractTemplatePaymentProject.setContractTemplateNumber(template.getContractTemplateNumber());
                        contractTemplatePaymentProject.setType(i);
                        contractTemplatePaymentProject.setLastUpdateTime(new Date());
                        contractTemplatePaymentProject.setOperatorId(tokenRedisVo.getId());
                        contractTemplatePaymentProject.setUpdateUserId(tokenRedisVo.getId());
                        contractTemplatePaymentProjectRepository.save(contractTemplatePaymentProject);
                    }
                    // 生成模板合同默认字段
                    Iterable<ContractTemplateDefaultField> all = contractTemplateDefaultFieldRepository.findAll();
                    for (ContractTemplateDefaultField contractTemplateDefaultField : all) {
                        ContractTemplateField contractTemplateField = new ContractTemplateField();
                        contractTemplateField.setContractTemplateNumber(template.getContractTemplateNumber());
                        contractTemplateField.setDefaultId(contractTemplateDefaultField.getId());
                        contractTemplateField.setMustStatus(1);
                        contractTemplateField.setLastUpdateTime(new Date());
                        contractTemplateField.setOperatorId(tokenRedisVo.getId());
                        contractTemplateField.setUpdateUserId(tokenRedisVo.getId());
                        contractTemplateFieldRepository.save(contractTemplateField);
                    }
                    // 生成模板合同自定义附件
                    Iterable<ContractAttachment> contractAttachmentList = contractAttachmentRepository.findAll();
                    for (ContractAttachment contractAttachment : contractAttachmentList) {
                        ContractTemplateCustomAttachment contractTemplateCustomAttachment = new ContractTemplateCustomAttachment();
                        contractTemplateCustomAttachment
                                .setContractTemplateNumber(template.getContractTemplateNumber());
                        contractTemplateCustomAttachment.setType(1);
                        contractTemplateCustomAttachment.setAttachmentId(contractAttachment.getId());
                        contractTemplateCustomAttachment.setStatus(1);
                        contractTemplateCustomAttachment.setOperatorStatus(1);
                        contractTemplateCustomAttachment.setLastUpdateTime(new Date());
                        contractTemplateCustomAttachment.setOperatorId(tokenRedisVo.getId());
                        contractTemplateCustomAttachment.setUpdateUserId(tokenRedisVo.getId());
                        contractTemplateCustomAttachmentRepository.save(contractTemplateCustomAttachment);
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }
}
